import useUserStore from '../store/user'

interface ResponseOptions {
    url: string
    headers?: { [key: string]: string }
    method?: 'OPTIONS' | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT'
    data?: { [key: string]: any }
    isSinglePost?: boolean
}

const userStore = useUserStore()

export const request = {
    isLock: false,
    http({ url = '', headers = {}, data = {}, method = 'POST', isSinglePost = false }: ResponseOptions) {
        const _this = this

        return new Promise(function (resolve, reject) {
            if (isSinglePost && _this.isLock) {
                reject({ message: '加载中' })
            }
            _this.isLock = true

            // #ifdef APP-PLUS
            url = import.meta.env.VITE_APP_BASE_URL + url
            // #endif
            // #ifdef H5
            url = import.meta.env.VITE_APP_BASE_PRE + url
            // #endif

            const header = Object.assign({ 'content-type': 'application/json', Authorization: '' }, headers)

            if (userStore.token) {
                header['Authorization'] = 'Bearer' + userStore.token
            }

            uni.request({
                url,
                header,
                method,
                data,
                success(res) {
                    const data = res.data as { code: number; data: object; msg: string }
                    switch (data.code) {
                        case 1005:
                            uni.showToast({ title: '登录状态已失效，请重新登录！', icon: 'none' })
                            setTimeout(() => uni.navigateTo({ url: 'pages/login/login' }), 1000)
                            break
                        case 200:
                            resolve(res.data)
                            break
                        default:
                            uni.showToast({ title: data.msg, icon: 'none', mask: true })
                            reject(res.data)
                            break
                    }
                },
                fail(err) {
                    uni.showToast({ title: '网络错误', icon: 'none' })
                    reject(err)
                },
                complete() {
                    _this.controller = null
                    _this.isLock = false
                }
            })
        })
    }
}
